﻿using BacklogParser.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BacklogParser.Parsers
{
    public static class ApplicantParser
    {
        public static List<Applicant> Parse(XElement parties)
        {
            var applicants = parties.Descendants(Constants.Epo + "applicants").ToList();
            return ParseApplicants(applicants);
        }

        private static List<Applicant> ParseApplicants(List<XElement> applicants)
        {
            var result = new List<Applicant>();

            foreach (var item in applicants)
            {
                var changeDateAttr = item.Attribute("change-date");
                var changeGazetteNumAttr = item.Attribute("change-gazette-num");


                var applicantsElems = item.Descendants(Constants.Epo + "applicant").ToList();

                foreach (var applicantElem in applicantsElems)
                {
                    
                    var addres = applicantElem.Descendants(Constants.Epo + "addressbook").First();
                    string sequence = "";
                    string appType = "";
                    string designation = "";

                    var sequenceAttr = applicantElem.Attribute("sequence");
                    if (sequenceAttr != null)
                        sequence = sequenceAttr.Value;

                    var appTypeAttr = applicantElem.Attribute("app-type");
                    if (appTypeAttr != null)
                        appType = appTypeAttr.Value;

                    var designationAttr = applicantElem.Attribute("designation");
                    if (designationAttr != null)
                        designation = designationAttr.Value;

                    // sequence = sequenceAttr?.Value;


                    var addressBook = AddressBookParser.Parse(addres);

                    var applicant = Applicant.Create(addressBook);
                    applicant.Sequence = sequence;
                    applicant.AppType = appType;
                    applicant.Designation = designation;

                    if (changeDateAttr != null)
                        applicant.ChangeDate = changeDateAttr.Value;

                    if (changeGazetteNumAttr != null)
                        applicant.ChangeGazetteNum = changeGazetteNumAttr.Value;


                    result.Add(applicant);
                }
            }

            return result;
        }
    }
}
